<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    use HasFactory;

    // 订单状态
    const STATUS_UNPAID = 'unpaid';
    const STATUS_PAID = 'paid';
    const STATUS_CANCELLED = 'cancelled';
    const STATUS_FREEZING = 'freezing';

    public static $statusMap = [
        self::STATUS_UNPAID     => '未支付',
        self::STATUS_PAID       => '已支付',
        self::STATUS_CANCELLED  => '已取消',
        self::STATUS_FREEZING   => '已冻结'
    ];

    // 退款状态
    const REFUND_STATUS_PENDING = 'pending';
    const REFUND_STATUS_APPLIED = 'applied';
    const REFUND_STATUS_PROCESSING = 'processing';
    const REFUND_STATUS_SUCCESS = 'success';
    const REFUND_STATUS_FAILED = 'failed';

    public static $refundStatusMap = [
        self::REFUND_STATUS_PENDING    => '未退款',
        self::REFUND_STATUS_APPLIED    => '已申请退款',
        self::REFUND_STATUS_PROCESSING => '退款中',
        self::REFUND_STATUS_SUCCESS    => '退款成功',
        self::REFUND_STATUS_FAILED     => '退款失败',
    ];

    const GATEWAY_WECHAT = 'wxpay';
    const GATEWAY_QQ = 'qqpay';
    const GATEWAY_ALI = 'alipay';

    public static $gatewayMap = [
        self::GATEWAY_WECHAT => '微信',
        self::GATEWAY_QQ => 'QQ',
        self::GATEWAY_ALI => '支付宝'
    ];

    protected $fillable = [
        'user_id', 'merchant_id', 'channel_id', 'status', 'from_url', 'title','trade_no', 'out_trade_no', 'total_amount', 'pay_amount', 'gateway', 'pay_user', 'payment_no', 'paid_at', 'client_ip', 'notify_url', 'return_url'
    ];

    public static function getOrderByTradeNo($tradeNo, $status = null)
    {
        $builder = self::query();
        $builder->where('trade_no', $tradeNo);
        if (!is_null($status)) $builder->where('status', $status);
        return $builder->firstOrFail();
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function merchant()
    {
        return $this->belongsTo(Merchant::class);
    }

    public function channel()
    {
        return $this->belongsTo(Channel::class);
    }
}
